#!/usr/bin/env python
"""
# -*- coding: utf-8 -*-
# @Time    : 2020/9/19 17:43
# @Author  : AshJo
# @Desc    : 作业：计算器
# @Filename: Calculator.py
# @Version : v1.0
"""

import re
from functools import reduce


# 计算两个数的乘法或者除法
def mul_div(exp):
    if '*' in exp:
        a, b = exp.split('*')
        return float(a) * float(b)
    if '/' in exp:
        a, b = exp.split('/')
        return float(a) / float(b)


# 计算两个数的加法或者减法
def add_sub(exp):
    if '+' in exp:
        a, b = exp.split('+')
        return float(a) + float(b)
    if '-' in exp:
        a, b = exp.split('-')
        return float(a) - float(b)


# 匹配乘除
def remove_muldiv(exp):
    while True:
        ret = re.search(r'\d+(\.\d+)?[*/]-?\d+(\.\d+)?', exp)
        if ret:
            son_exp = ret.group()
            res = mul_div(son_exp)
            exp = exp.replace(son_exp, str(res))
        else:
            break
    return exp


# 匹配加减
def remove_addsub(exp):
    ret = re.findall('[-+]?\d+(?:\.\d+)?', exp)
    res = reduce(lambda a, b: float(a) + float(b), ret)
    return res


# 匹配括号
def remove_kuohao(exp):
    kuohao = re.search(r'[(](.*?)[)]', exp)
    k1 = kuohao.group()
    k2 = remove_muldiv(k1)
    k3 = remove_addsub(k2)
    while True:
        ret1 = re.search(r'\((-?\d+(\.\d+)?)\)', exp)
        ret2 = re.search(r'\d+(\.\d+)', exp)
        if ret1 and ret2:
            son_exp1 = ret1.group()
            son_exp2 = ret2.group()
            exp = exp.replace(son_exp1, son_exp2)
        else:
            break
    return exp


def exp_fmt(exp):
    while re.search('[+-]{2,}', exp):
        exp = exp.replace('+-', '-')
        exp = exp.replace('-+', '-')
        exp = exp.replace('++', '+')
        exp = exp.replace('--', '+')
    return exp


exp = '-10++5-+6*(1*3*4*5/6-9)+-4'

ret1 = exp_fmt(exp)
ret2 = remove_kuohao(ret1)
# ret3 = remove_addsub(ret2)
# ret3 = remove_kuohao(ret2)
# ret4 = remove_addsub(ret3)
# print(ret2)
